<template>
  <div>
    <FilterInput
      ref="FilterToolRef"
      v-model="paramsObj"
      :filter-list="filterList"
      :show-advanced-filter="false"
      style="margin-bottom: 12px"
      show-search-btn
      @handelClick="queryClick"
      @queryEmpty="queryEmpty"/>
    <el-table
      v-loading="tableLoading"
      ref="customeTransferTable"
      :data="customTableData"
      height="400px"
      tooltip-effect="dark"
      style="width: 100%"
      border
      @select="handleSelectRow"
      @select-all="handleSelectAll">
      <el-table-column
        type="selection"
        width="55" />
      <el-table-column width="120" align="left">
        <template slot="header" slot-scope="scope">
          <span style="color: #f56c6c;">*</span>
          <span class="label">模块</span>
        </template>
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="left" min-width="200">
        <template slot="header" slot-scope="scope">
          <span style="color: #f56c6c;">*</span>
          <span class="label">交接内容</span>
        </template>
        <template slot-scope="scope">
          <el-checkbox-group v-model="scope.row.contentsIds" class="status-checkbox">
            <el-checkbox
              v-for="(item, index) in scope.row.transferContent"
              :key="index"
              :label="item.status"
              :disabled="!(mulIds.includes(scope.row.formId))"
              @change="selContentId($event, item)">
              <span>{{ item.name }}：</span>
              <span :class="(item.ids.length - item.removeIds.length) > 0 ? 'red-num' : ''">{{ (item.ids.length - item.removeIds.length) }}</span> /
              <span>{{ (item.ids && item.ids.length) ? item.ids.length : 0 }}</span>
              <el-button v-if="item.ids && item.ids.length > 0" type="text" style="margin-left: 10px;" @click="openCustomDialog(item, scope.row)">查看明细</el-button>
            </el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column min-width="180">
        <template slot="header" slot-scope="scope">
          <span style="color: #f56c6c;">*</span>
          <span class="label">交接角色</span>
        </template>
        <template slot-scope="scope">
          <el-checkbox-group v-model="scope.row.roleIds" class="role-checkbox" @change="selRoleType($event, scope.row)">
            <el-checkbox
              v-for="(item, index) in scope.row.roles"
              :key="index"
              :label="item.value"
              :disabled="!(mulIds.includes(scope.row.formId))">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="交接说明"
        width="350px"
        show-overflow-tooltip />
    </el-table>
    <div class="pagination-flex">
      <el-pagination
        v-show="customFlowData.length > 0"
        :current-page.sync="page"
        :page-size="perPage"
        :total="customFlowData.length"
        :page-sizes="[10, 20, 50]"
        small
        layout="sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import { getTransfereeCount } from '@/api/user';
import { getProcessManagement } from '@/api/legal';
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import tableSelections from '@/mixins/tableSelections';
import handOver from '../mixin';

export default {
  mixins: [tableSelections, handOver],
  props: {
    handoverId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      tableLoading: false,
      multipleSelectionAll: [],
      moduleRoleData: {},
      customFlowData: [], // 自定义表单流程
      customFlowDataAll: [],
      filterList: [{ keyword: 'name', name: '模块名称', type: 'input', placeholder: '请输入模块名称' }],
      paramsObj: {},
      page: 1,
      perPage: 10,
      customTableData: [],
      tableRefName: 'customeTransferTable', // 表格的ref名称
      // idKey: 'id', // 唯一表示字段
      idKey: 'formId', // 唯一表示字段
      mulIds: []
    };
  },
  watch: {
    customTableData: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val);
        });
      },
      deep: true
    }
  },
  created() {
    this.getCustomFlow();
  },
  methods: {
    hasRouteAuth,
    resetData() {
      this.clearTableSelection();
      this.multipleSelectionAll = [];
      this.mulIds = [];
      this.customFlowData = this.customFlowDataAll;
      this.paramsObj = {};
      this.handleData(this.customFlowData);
    },
    tableSelectionChange() {
      this.mulIds = this.multipleSelectionAll.map(item => item[this.idKey]);
    },
    clearTableSelection() {
      if (this.$refs.customeTransferTable && this.$refs.customeTransferTable.clearSelection) {
        this.$refs.customeTransferTable.clearSelection();
      }
    },
    handleSelectRow(selection, item) {
      if (!this.handoverId) {
        ElMessage.warning('请先选择交接人！');
        this.clearTableSelection();
        return;
      }
      // 当前勾选的模块
      this.selectTable(selection, item);
      this.tableSelectionChange();
      if (!this.mulIds.includes(item.formId)) {
        // 模块未勾选,模块后面取消勾选
        item.contentsIds = [];
        item.roleIds = [];
        item.transferContent.map(cur => {
          cur.ids = [];
          cur.removeIds = [];
        });
      } else {
        // 模块勾选
        getTransfereeCount({
          handoverId: this.handoverId,
          businessType: item.businessType,
          formId: item.formId
        }).then(res => {
          this.formatData(res, item, this);
        }).catch(err => {
          console.log(err);
        });
      }
    },
    handleSelectAll(val) {
      if (!this.handoverId) {
        ElMessage.warning('请先选择交接人！');
        this.clearTableSelection();
        return;
      }
      if (val) {
        // 勾选模块,后面交接内容和角色全选
        this.selectTable(val);
        this.tableSelectionChange();
        // 创建请求数组
        const promiseArr = [];
        val.forEach(item => {
          promiseArr.push(this.createPromise(item, true));
        });
        // 串行执行请求
        this.executePromise(promiseArr);
      }
      // 不勾选模块,模块后面取消勾选
      this.customFlowData.forEach(item => {
        if (!this.mulIds.includes(item.formId)) {
          item.contentsIds = [];
          item.roleIds = [];
          item.transferContent.map(cur => {
            cur.ids = [];
            cur.removeIds = [];
          });
        }
      });
    },
    async getCustomFlow() {
      this.tableLoading = true;
      const { data } = await getProcessManagement({ type: 1 });
      this.tableLoading = false;
      this.customFlowData = this.flatTree(data);
      this.handleData(this.customFlowData);
      this.$emit('emitGetCustomData', this.customFlowData.length);
      this.customFlowDataAll = _.cloneDeep(this.customFlowData);
    },
    handleData(data) {
      this.customTableData = data.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.handleData(this.customFlowData);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.handleData(this.customFlowData);
    },
    queryClick() {
      if (this.paramsObj.name) {
        this.customFlowData = this.customFlowDataAll.filter(item => {
          return item.name.indexOf(this.paramsObj.name) !== -1;
        });
      } else {
        this.customFlowData = this.customFlowDataAll;
      }
      this.handleData(this.customFlowData);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.customFlowData = this.customFlowDataAll;
      this.handleData(this.customFlowData);
    },
    flatTree(treeData) {
      let res = [];
      treeData.forEach(item => {
        if (item.children) {
          item.children = item.children.filter(ele => {
            if (ele.isCustom) {
              ele.businessType = 15;
              ele.transferContent = [
                { status: 5, name: '待提交', ids: [], removeIds: [] },
                { status: 1, name: '审批中', ids: [], removeIds: [] }
              ];
              ele.roles = [
                { value: 0, label: '创建人' },
                { value: 1, label: '审批人' }
              ];
              ele.headData = [
                { label: '流水号', property: 'sn' },
                { label: '创建人', property: 'creator' },
                { label: '创建时间', property: 'createTime', type: 'minute', millisecond: true }
              ];
              ele.remark = '转交创建人和审批人';
              ele.roleIds = [];
              ele.roleData = [];
              ele.contentsIds = [];
              return ele;
            }
          });
          res = res.concat(item.children);
        }
      });
      return res;
    },
    openCustomDialog(item, row) {
      this.$emit('openCustomDialog', { item, row });
    }
  }
};
</script>
<style lang="scss" scoped>
.el-checkbox{
  display: block;
  margin-bottom: 10px;
}
.el-table {
  .status-checkbox{
    &::v-deep{
      .el-checkbox {
        pointer-events: none;
      }
      .el-checkbox__input,.el-checkbox__label {
        pointer-events: all;
      }
      .el-checkbox__input.is-checked+.el-checkbox__label{
        color: #999;
      }
      .red-num{
        color: #FF4E5F;
      }
    }
  }
}
.pagination-flex {
  display: flex;
  justify-content: flex-end;
}
</style>
